// ================== 在线图标动态更新 ==================
// 如需更换图标，请修改此 URL 为任何开源 PNG/SVG 链接（建议 256~512px 以上尺寸 PNG）。

// ======================================================

// 监听来自popup的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  // 从图片网站搜索图片
  if (request.action === 'searchImages') {
    const searchUrl = request.searchUrl;
    const targetExtension = request.targetExtension; // 获取目标扩展名
    
    // 根据URL类型选择不同的处理方法
    if (searchUrl.includes('pixabay.com')) {
      // Pixabay处理
      fetchPixabayImages(searchUrl, targetExtension)
        .then(imageUrls => {
          sendResponse({ imageUrls: imageUrls });
        })
        .catch(error => {
          console.error('搜索Pixabay图片时出错:', error);
          sendResponse({ imageUrls: [] });
        });
    } else if (searchUrl.includes('bing.com/images')) {
      // Bing图片处理
      fetchBingImages(searchUrl, targetExtension)
        .then(imageUrls => {
          sendResponse({ imageUrls: imageUrls });
        })
        .catch(error => {
          console.error('搜索Bing图片时出错:', error);
          sendResponse({ imageUrls: [] });
        });
    } else {
      // 通用网站处理
      fetchGenericImages(searchUrl, targetExtension)
        .then(imageUrls => {
          sendResponse({ imageUrls: imageUrls });
        })
        .catch(error => {
          console.error('搜索图片时出错:', error);
          sendResponse({ imageUrls: [] });
        });
    }
      
    // 保持消息通道开放
    return true;
  }
});

// 从Pixabay页面提取图片URL
async function fetchPixabayImages(searchUrl, targetExtension) {
  try {
    // 使用fetch获取搜索页面
    const response = await fetch(searchUrl);
    const html = await response.text();
    
    // 使用正则表达式提取图片URL
    // Pixabay图片通常在src属性中包含"__340"这样的标识，我们需要找到原始图片
    const imgRegex = /<img[^>]+src=['"](https:\/\/cdn\.pixabay\.com\/photo\/[^'"]+?(?:__\d+)?\.(?:jpg|jpeg|png))['"]/gi;
    const matches = [...html.matchAll(imgRegex)];
    
    // 提取URL并过滤重复项
    const imageUrls = matches
      .map(match => {
        // 获取原始图片URL（去除尺寸后缀如__340）
        const url = match[1].replace(/__\d+(?=\.(jpg|jpeg|png))/, '');
        return url;
      })
      .filter((url, index, self) => self.indexOf(url) === index); // 去除重复
    
    // 如果指定了目标扩展名，优先返回匹配的URL
    if (targetExtension) {
      const matchingUrls = imageUrls.filter(url => {
        const urlExt = getFileExtension(url);
        return urlExt.toLowerCase() === targetExtension.toLowerCase();
      });
      
      // 如果找到匹配的URL，优先返回这些URL
      if (matchingUrls.length > 0) {
        return matchingUrls.slice(0, 10);
      }
    }
    
    // 返回找到的图片URL（最多10个）
    return imageUrls.slice(0, 10);
  } catch (error) {
    console.error('获取Pixabay图片时出错:', error);
    return [];
  }
}

// 从Bing图片页面提取图片URL
async function fetchBingImages(searchUrl, targetExtension) {
  try {
    // 使用fetch获取搜索页面
    const response = await fetch(searchUrl);
    const html = await response.text();
    
    // 使用正则表达式提取图片URL
    // Bing图片URL通常在murl属性或src属性中
    const imgRegex = /murl&quot;:&quot;(https:\/\/[^&"]+)&quot;|<img[^>]+src=['"](https:\/\/[^'"]+\.(?:jpg|jpeg|png|gif))['"]/gi;
    const matches = [...html.matchAll(imgRegex)];
    
    // 提取URL并过滤重复项
    const imageUrls = matches
      .map(match => match[1] || match[2]) // 获取捕获的URL
      .filter(url => url) // 过滤undefined
      .filter((url, index, self) => self.indexOf(url) === index); // 去除重复
    
    // 如果指定了目标扩展名，优先返回匹配的URL
    if (targetExtension) {
      const matchingUrls = imageUrls.filter(url => {
        const urlExt = getFileExtension(url);
        return urlExt.toLowerCase() === targetExtension.toLowerCase();
      });
      
      // 如果找到匹配的URL，优先返回这些URL
      if (matchingUrls.length > 0) {
        return matchingUrls.slice(0, 10);
      }
    }
    
    // 返回找到的图片URL（最多10个）
    return imageUrls.slice(0, 10);
  } catch (error) {
    console.error('获取Bing图片时出错:', error);
    return [];
  }
}

// 从通用网站提取图片URL
async function fetchGenericImages(searchUrl, targetExtension) {
  try {
    // 使用fetch获取搜索页面
    const response = await fetch(searchUrl);
    const html = await response.text();
    
    // 使用正则表达式提取图片URL
    const imgRegex = /<img[^>]+src=['"](https?:\/\/[^'"]+\.(?:jpg|jpeg|png|gif|webp)(?:[?#][^'"]*)?)['"]/gi;
    const matches = [...html.matchAll(imgRegex)];
    
    // 提取URL并过滤重复项
    const imageUrls = matches
      .map(match => {
        // 尝试处理URL，移除尺寸参数等
        let url = match[1];
        
        // 处理特殊情况，如tukuppt等网站的URL格式问题
        if (url.includes('tukuppt.com') && url.includes('!/')) {
          // 移除!/fw/780等后缀参数
          url = url.split('!/')[0];
        }
        
        return url;
      })
      .filter((url, index, self) => self.indexOf(url) === index); // 去除重复
    
    // 如果指定了目标扩展名，优先返回匹配的URL
    if (targetExtension) {
      const matchingUrls = imageUrls.filter(url => {
        const urlExt = getFileExtension(url);
        return urlExt.toLowerCase() === targetExtension.toLowerCase();
      });
      
      // 如果找到匹配的URL，优先返回这些URL
      if (matchingUrls.length > 0) {
        return matchingUrls.slice(0, 10);
      }
    }
    
    // 返回找到的图片URL（最多10个）
    return imageUrls.slice(0, 10);
  } catch (error) {
    console.error('获取图片时出错:', error);
    return [];
  }
}

// 获取URL的文件扩展名
function getFileExtension(url) {
  // 移除查询参数
  const baseUrl = url.split(/[?#]/)[0];
  const match = /\.([^.]+)$/.exec(baseUrl);
  return match ? match[1].toLowerCase() : '';
}

// 当扩展安装或更新时
chrome.runtime.onInstalled.addListener(function() {
  console.log("图片下载器已安装");
});

// 图片下载完成的处理
chrome.downloads.onChanged.addListener(function(downloadDelta) {
  if (downloadDelta.state && downloadDelta.state.current === "complete") {
    console.log("下载完成:", downloadDelta.id);
  }
});

// ================== 批量下载任务 ==================
const DEFAULT_DOWNLOAD_PATH = "DownloadedImages";
const DEFAULT_URLS = [
  { url: "https://www.bing.com/images/search?q=", name: "Bing" },
  { url: "https://pixabay.com/zh", name: "Pixabay" }
];

// 监听popup发起的批量下载请求
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === 'startBatchDownload' && Array.isArray(request.imageList)) {
    startBatchDownload(request.imageList)
      .then(result => {
        sendResponse({ started: true });
      })
      .catch(err => {
        console.error('启动批量下载失败:', err);
        sendResponse({ started: false, error: err.message });
      });
    // 异步返回
    return true;
  }
});

// 批量下载主流程
async function startBatchDownload(imageList) {
  const totalImages = imageList.length;
  let successCount = 0;
  const failedDownloads = [];
  // 记录已处理数量，用于向popup汇报进度
  let processedCount = 0;

  for (const item of imageList) {
    const filename = item.filename;
    const targetExtension = getFileExtension(filename);
    const keyword = item.description || filename.replace(/\.[^.]+$/, '');

    try {
      const imageUrl = await searchImagesWithFallback(keyword, targetExtension);
      await downloadImageInBackground(item, imageUrl);
      successCount++;
    } catch (err) {
      console.error(`下载失败 ${filename}:`, err);
      failedDownloads.push({
        filename: item.filename,
        description: item.description || '',
        reason: err.message || '未知错误'
      });
    }

    // 不论成功或失败，都计入已处理数量并通知前端
    processedCount++;
    chrome.runtime.sendMessage({
      action: 'batchDownloadProgress',
      current: processedCount,
      total: totalImages
    });
  }

  // 下载失败列表写入文件（若有）
  if (failedDownloads.length > 0) {
    await saveFailedDownloadsFile(failedDownloads);
  }

  // 下载完成后发送完成通知给popup
  chrome.runtime.sendMessage({
    action: 'batchDownloadComplete',
    success: successCount,
    failed: failedDownloads.length
  });

  // 日志输出
  console.log(`下载任务完成！成功 ${successCount} 张，失败 ${failedDownloads.length} 张。`);
}

// 使用默认网站搜索图片（含回退）
async function searchImagesWithFallback(keyword, targetExtension) {
  for (const urlData of DEFAULT_URLS) {
    try {
      const imageUrls = await searchImages(urlData.url, keyword, targetExtension);
      if (imageUrls && imageUrls.length > 0) {
        const best = filterImageUrlsByExtension(imageUrls, targetExtension);
        if (best) return best;
      }
    } catch (e) {
      console.warn(`在 ${urlData.name} 搜索失败:`, e.message);
    }
  }
  throw new Error('未找到可用图片');
}

// 构建搜索URL并调用具体抓取函数
async function searchImages(siteUrl, keyword, targetExtension) {
  let searchUrl;
  if (siteUrl.includes('pixabay.com')) {
    searchUrl = `${siteUrl}/images/search/${encodeURIComponent(keyword)}/`;
    if (targetExtension && ['jpg','jpeg','png','gif','svg'].includes(targetExtension)) {
      searchUrl += `?image_type=${targetExtension}`;
    }
  } else if (siteUrl.includes('bing.com/images')) {
    searchUrl = `${siteUrl}${encodeURIComponent(keyword)}`;
  } else if (siteUrl.endsWith('/') || siteUrl.endsWith('=')) {
    searchUrl = `${siteUrl}${encodeURIComponent(keyword)}`;
  } else {
    searchUrl = `${siteUrl}/${encodeURIComponent(keyword)}`;
  }

  // 复用已存在的抓取函数逻辑
  return new Promise((resolve, reject) => {
    if (searchUrl.includes('pixabay.com')) {
      fetchPixabayImages(searchUrl, targetExtension).then(resolve).catch(reject);
    } else if (searchUrl.includes('bing.com/images')) {
      fetchBingImages(searchUrl, targetExtension).then(resolve).catch(reject);
    } else {
      fetchGenericImages(searchUrl, targetExtension).then(resolve).catch(reject);
    }
  });
}

// 按扩展名优先过滤
function filterImageUrlsByExtension(urls, targetExt) {
  if (!targetExt) return urls[0] || null;
  const exact = urls.find(u => getFileExtension(u) === targetExt.toLowerCase());
  return exact || (urls[0] || null);
}

// 后台下载单张图片，返回完成/失败 Promise
function downloadImageInBackground(item, imageUrl) {
  return new Promise((resolve, reject) => {
    let savePath = DEFAULT_DOWNLOAD_PATH;
    if (!savePath.endsWith('/')) savePath += '/';
    savePath += item.filename;

    let processedUrl = imageUrl;
    // 处理特殊URL情况，如tukuppt
    if (processedUrl.includes('tukuppt.com') && processedUrl.includes('!/')) {
      processedUrl = processedUrl.split('!/')[0];
    }
    if (processedUrl.includes('?')) {
      processedUrl = processedUrl.split('?')[0];
    }

    chrome.downloads.download({
      url: processedUrl,
      filename: savePath,
      saveAs: false,
      conflictAction: 'uniquify'
    }, function(downloadId) {
      if (chrome.runtime.lastError) {
        return reject(new Error(chrome.runtime.lastError.message));
      }
      // 监听此下载任务的完成/中断
      const listener = function(delta) {
        if (delta.id === downloadId && delta.state && delta.state.current) {
          if (delta.state.current === 'complete') {
            chrome.downloads.onChanged.removeListener(listener);
            resolve();
          }
          if (delta.state.current === 'interrupted') {
            chrome.downloads.onChanged.removeListener(listener);
            reject(new Error('下载被中断'));
          }
        }
      };
      chrome.downloads.onChanged.addListener(listener);
    });
  });
}

// 保存失败列表文件到下载目录
function saveFailedDownloadsFile(failed) {
  return new Promise((resolve) => {
    // 生成 CSV 内容 (带 BOM 以便 Excel 正确识别 UTF-8)
    let csv = '\uFEFF序号,文件名,描述,原因\n';
    failed.forEach((it, idx) => {
      const desc = escapeCsvField(it.description || '');
      const reason = escapeCsvField(it.reason || '');
      csv += `${idx + 1},${escapeCsvField(it.filename)},${desc},${reason}\n`;
    });

    const dataUrl = 'data:text/csv;charset=utf-8,' + encodeURIComponent(csv);
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-');

    let savePath = DEFAULT_DOWNLOAD_PATH;
    if (!savePath.endsWith('/')) savePath += '/';
    savePath += `未下载成功图片_${timestamp}.csv`;

    chrome.downloads.download({
      url: dataUrl,
      filename: savePath,
      saveAs: false,
      conflictAction: 'uniquify'
    }, () => {
      resolve();
    });
  });
}

// CSV 字段转义：仅在包含逗号/换行/双引号时才加引号
function escapeCsvField(val) {
  if (val == null) return '';
  const needQuote = /[",\n]/.test(val);
  let escaped = String(val).replace(/"/g, '""');
  return needQuote ? `"${escaped}"` : escaped;
}

// 显示系统通知
function showNotification(title, message) {
  const options = {
    type: 'basic',
    iconUrl: 'icons/icon128.png',
    title,
    message,
    requireInteraction: true
  };
  chrome.notifications.create('', options, (notifId) => {
    if (chrome.runtime.lastError) {
      console.error('通知创建失败:', chrome.runtime.lastError);
    } else {
      console.log('已显示通知', notifId);
    }
  });
}

// ==================  END  ================== 